package com.itheima.filter;

import com.itheima.utill.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class FilterToken implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //servletRequest    请求      servletResponse响应   filterChain放行
        //获取请求
        HttpServletRequest Request = (HttpServletRequest) servletRequest;
        HttpServletResponse Response = (HttpServletResponse) servletResponse;
        //获取请求路径, 将Request中的url以字符串的形式存储起来
        String url = Request.getRequestURL().toString();
        if(url.contains("login")){
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return ;
        }
            //获取请求体
        String jwt = Request.getHeader("token");
        if(jwt == null || jwt.isEmpty()){
            //不存在, 响应401
            System.out.println("孩子们牢大来了");
            Response.setStatus(401);
            return;
        }

        try {
            //解析token
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            //有异常响应401
            System.out.println("孩子们我们没救了");
            Response.setStatus(401);
            return;
        }
        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
